from stockpyle.stores import *

# TODO: support imports of other stores
class Stacker(object):
    """Represents a collection of stores.  Input is a 'blueprint', which
    is a dictionary representation of all the stores you want to create.
    
    The following example creates two stores, named 'my_shove_store' and
    'my_threadlocal_store'.  The store's classname is given, along with
    the keyword arguments needed to instantiate that store:
    
        blueprint = {
            "my_shove_store": {
                "class": "ShoveStore",
                "args": {
                    "shoveuri": "file:///stockpyle.tmp"
                    },
                },
            "my_threadlocal_store": {
                "class": "Threadlocal",
                "args": {},
                }
            }
    """
    
    blueprint = property(lambda self: self.__blueprint)
    """the dictionary used to instantiate this Stacker"""
    
    def __init__(self, blueprint):
        store_lookup = {}
        for store_name in blueprint:
            classname = blueprint[store_name]["class"]
            klass = globals().get(classname, None)
            if not klass or not issubclass(klass, BaseStore):
                raise StandardError("'%s' is not a valid store name" % classname)
            kwargs = blueprint[store_name].get("args", {})
            if classname == "ChainedStore":
                # chained get special treatment
                kwargs["stores"] = [store_lookup[store_name] for store_name in kwargs["stores"]]
            # instantiate a store mapped to its name
            store_lookup[store_name] = klass(**kwargs)
        self.__store_lookup = store_lookup
        self.__blueprint = blueprint
    
    def get_store(self, name):
        return self.__store_lookup.get(name, None)